import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';
import styles from './editor.module.css';
import { uploadFile } from '../../apis/public/upload';
import { DownloadOutlined } from '@ant-design/icons';
import './customBtn';
import { Editor_Default_Directory } from '@/globals/document';

interface RichEditorProps {
  value?: string;
  onChange?: (html: string) => void;
  placeholder?: string;
  readOnly?: boolean;
  className?: string;
  style?: React.CSSProperties;
  onExport?: () => void;
  onUpload?: () => void;
}

export interface RichEditorRef {
  insertText: (text: string) => void;
  getEditor: () => IDomEditor | null;
}

// 定义上传图片接口返回结构
interface UploadImageResponse {
  data: {
    url: string;
  };
}

const RichEditor = forwardRef<RichEditorRef, RichEditorProps>(({
  value = '',
  onChange,
  placeholder = '请输入内容...',
  readOnly = false,
  className = '',
  style = {},
  onExport,
  onUpload
}, ref) => {
  // 编辑器实例
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  // 编辑器内容
  const [html, setHtml] = useState(value);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    // 在当前光标位置插入文本
    insertText: (text: string) => {
      if (editor) {
        editor.insertText(text);
      }
    },
    // 获取编辑器实例
    getEditor: () => editor
  }));

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    toolbarKeys: [
      'undo',
      'redo',
      '|',
      'bold',
      'italic',
      'underline',
      'through',
      'color',
      'bgColor',
      '|',
      'fontSize',
      'fontFamily',
      'lineHeight',
      '|',
      'bulletedList',
      'numberedList',
      'todo',
      '|',
      'justifyLeft',
      'justifyCenter',
      'justifyRight',
      '|',
      'insertLink',
      'uploadImage',
      'insertTable',
      '|',
      'export',
      'upload',
    ],
    /*insertKeys: {
      index: 26,
      keys: ['myButton']
    }*/
  };

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder,
    readOnly,
    autoFocus: false,
    MENU_CONF: {
      uploadImage: {
        server: '/api/starhub/document/addDocumentInfo',
        fieldName: 'file',
        maxFileSize: 10 * 1024 * 1024, // 10M
        maxNumberOfFiles: 10,
        allowedFileTypes: ['image/*'],
        customUpload: async (file: File, insertFn: (url: string) => void) => {
          try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('fileName', file instanceof File ? file.name : 'unknown');
            formData.append('directoryId', Editor_Default_Directory.toString());
            const response = await uploadFile(formData);
            if (response.code === 200) {
              insertFn(`/api/starhub/document/download/${response.data.page?.[0].id}`);
            } else {
              throw new Error(response.message || 'Upload failed');
            }
          } catch (error) {
            console.error('Image upload failed:', error);
            throw error;
          }
        },
      },
      fontSize: {
        fontSizeList: [
          // pt 单位，10-36pt，间隔2
          '10pt', '12pt', '14pt', '16pt', '18pt', '20pt', '22pt', '24pt', '26pt', '28pt', '30pt', '32pt', '34pt', '36pt',
          // px 单位，10-48px，间隔2
          '10px', '12px', '14px', '16px', '18px', '20px', '22px', '24px', '26px', '28px', '30px', '32px', '34px', '36px', '38px', '40px', '42px', '44px', '46px', '48px'
        ],
      },
      lineHeight: {
        lineHeightList: ['1', '1.5', '2', '2.5', '48pt', '50pt', '52pt', '56pt', '64pt'],
      },
      fontFamily: {
        fontFamilyList: ['黑体', '楷体', '仿宋', 'Arial', 'Tahoma', 'Verdana', 'Times New Roman',
          'FangSong', 'SimHei', 'SimSun', 'KaiTi', 'FZXiaoBiaoSong',
          'FZXiaoBiaoSong-B05S', 'FangSong_GB2312',
          'Microsoft YaHei', 'sans-serif',
        ],
      },
      export: {
        execFunc: typeof onExport === 'function' ? onExport : () => { }
      },
      upload: {
        execFunc: typeof onUpload === 'function' ? onUpload : () => {}
      }
    },
  };

  // 及时销毁编辑器
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // 同步外部传入的内容
  useEffect(() => {
    if (value !== html) {
      setHtml(value);
    }
  }, [value]);

  // 内容变化时触发
  const handleChange = (editor: IDomEditor) => {
    const newHtml = editor.getHtml();
    setHtml(newHtml);
    onChange?.(newHtml);
  };

  return (
    <div className={`${styles['statHub-editor-container']} ${className}`} style={style}>
      <div style={{ position: 'relative' }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          className={styles['statHub-editor-toolbar']}
        />
      </div>
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={handleChange}
        className={styles['statHub-editor-content']}
      />
    </div>
  );
});

export default RichEditor;
